/**
 * 库存管理页面JavaScript逻辑
 */

let currentMode = 'all'; // all, low-stock
let vaccineList = [];

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.SITE_ADMIN)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 检查并显示低库存预警
    await checkAndShowLowStockAlert();

    // 加载库存列表
    await loadInventoryList();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '管理员';
        document.getElementById('userName').textContent = userName;

        // 设置头像首字母
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
    }
}

/**
 * 加载库存列表
 */
async function loadInventoryList() {
    currentMode = 'all';
    document.getElementById('listTitle').textContent = '库存列表';

    try {
        const inventories = await HttpClient.get('/admin/inventory/list');
        displayInventories(inventories);
    } catch (error) {
        console.error('加载库存列表失败:', error);
        UI.showMessage('加载库存列表失败', 'danger');
    }
}

/**
 * 加载低库存预警
 */
async function loadLowStockAlerts() {
    currentMode = 'low-stock';
    document.getElementById('listTitle').textContent = '低库存预警';

    try {
        // 传递threshold参数，阈值为10
        const alerts = await HttpClient.get('/admin/inventory/low-stock-alert?threshold=10');
        displayLowStockAlerts(alerts);

        if (alerts.length > 0) {
            UI.showMessage(`发现 ${alerts.length} 个低库存预警`, 'warning');
        } else {
            UI.showMessage('库存充足，暂无预警', 'success');
        }
    } catch (error) {
        console.error('加载低库存预警失败:', error);
        UI.showMessage('加载低库存预警失败', 'danger');
    }
}

/**
 * 显示低库存预警列表（使用LowStockAlertVO数据结构）
 */
function displayLowStockAlerts(alerts) {
    const tbody = document.getElementById('inventoryTableBody');
    tbody.innerHTML = '';

    if (!alerts || alerts.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
                    <i class="fas fa-boxes" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                    库存充足，暂无预警
                </td>
            </tr>
        `;
        return;
    }

    alerts.forEach(alert => {
        const row = document.createElement('tr');

        // 低库存预警总是显示红色
        const quantityStyle = 'color: #f5222d; font-weight: bold;';
        
        // 获取疫苗类型
        let vaccineTypeDisplay = '<span class="badge badge-secondary">-</span>';
        if (alert.vaccineType !== undefined && alert.vaccineType !== null) {
            vaccineTypeDisplay = `<span class="badge badge-info">${Format.vaccineType(alert.vaccineType)}</span>`;
        } else if (alert.vaccineId) {
            vaccineTypeDisplay = '<span class="badge badge-info">未知</span>';
        }

        row.innerHTML = `
            <td>${alert.vaccineName || '未关联疫苗'}</td>
            <td>${vaccineTypeDisplay}</td>
            <td style="${quantityStyle}">${alert.count || 0}</td>
            <td>10</td>
            <td>-</td>
            <td>-</td>
            <td>
                <button class="btn btn-primary btn-sm" onclick="showUpdateInventoryModal(${alert.id}, '${(alert.vaccineName || '未关联疫苗').replace(/'/g, "\\'")}', ${alert.count || 0})">
                    <i class="fas fa-edit"></i> 更新
                </button>
                <button class="btn btn-danger btn-sm" onclick="handleDeleteInventory(${alert.id}, '${(alert.vaccineName || '未关联疫苗').replace(/'/g, "\\'")}')" style="margin-left: 5px;">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

/**
 * 显示库存列表（使用InventoryVO数据结构）
 */
function displayInventories(inventories) {
    const tbody = document.getElementById('inventoryTableBody');
    tbody.innerHTML = '';

    if (!inventories || inventories.length === 0) {
        const message = currentMode === 'low-stock' ? '库存充足，暂无预警' : '暂无库存记录';
        tbody.innerHTML = `
            <tr>
                <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
                    <i class="fas fa-boxes" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                    ${message}
                </td>
            </tr>
        `;
        return;
    }

    inventories.forEach(inventory => {
        const row = document.createElement('tr');

        // 判断是否低库存
        const isLowStock = inventory.quantity < inventory.lowStockThreshold;
        const quantityStyle = isLowStock ? 'color: #f5222d; font-weight: bold;' : '';

        row.innerHTML = `
            <td>${inventory.vaccineName || '-'}</td>
            <td>
                <span class="badge badge-info">${Format.vaccineType(inventory.vaccineType)}</span>
            </td>
            <td style="${quantityStyle}">${inventory.quantity || 0}</td>
            <td>${inventory.lowStockThreshold || 100}</td>
            <td>${Format.date(inventory.productionDate)}</td>
            <td>${Format.date(inventory.expirationDate)}</td>
            <td>
                <button class="btn btn-primary btn-sm" onclick="showUpdateInventoryModal(${inventory.id}, '${inventory.vaccineName}', ${inventory.quantity})">
                    <i class="fas fa-edit"></i> 更新
                </button>
                <button class="btn btn-danger btn-sm" onclick="handleDeleteInventory(${inventory.id}, '${(inventory.vaccineName || '未关联疫苗').replace(/'/g, "\\'")}')" style="margin-left: 5px;">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

/**
 * 显示添加库存模态框
 */
async function showAddInventoryModal() {
    document.getElementById('addInventoryModal').classList.add('show');
    document.getElementById('addInventoryForm').reset();

    // 加载疫苗列表
    await loadVaccineList();
}

/**
 * 关闭添加库存模态框
 */
function closeAddInventoryModal() {
    document.getElementById('addInventoryModal').classList.remove('show');
}

/**
 * 加载疫苗列表
 */
async function loadVaccineList() {
    try {
        // 获取所有疫苗（设置较大的pageSize）
        const pageData = await HttpClient.get('/vaccine/list?pageNum=1&pageSize=1000');
        vaccineList = pageData.records || [];

        const select = document.getElementById('vaccineId');
        select.innerHTML = '<option value="">请选择疫苗</option>';

        if (vaccineList.length === 0) {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '暂无可用疫苗';
            option.disabled = true;
            select.appendChild(option);
        } else {
            vaccineList.forEach(vaccine => {
                const option = document.createElement('option');
                option.value = vaccine.id;
                option.textContent = `${vaccine.name} - ${Format.vaccineType(vaccine.type)}`;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载疫苗列表失败:', error);
        UI.showMessage('加载疫苗列表失败: ' + error.message, 'danger');
    }
}

/**
 * 处理添加库存
 */
async function handleAddInventory() {
    const vaccineId = document.getElementById('vaccineId').value;
    const quantity = document.getElementById('quantity').value;

    // 表单验证
    if (!vaccineId) {
        UI.showMessage('请选择疫苗', 'warning');
        return;
    }

    if (!quantity || quantity <= 0) {
        UI.showMessage('请输入有效的库存数量', 'warning');
        return;
    }

    try {
        const data = {
            vaccineId: parseInt(vaccineId),
            count: parseInt(quantity)
        };

        await HttpClient.post('/admin/inventory', data);

        UI.showMessage('添加库存成功', 'success');
        closeAddInventoryModal();

        // 重新加载库存列表
        await loadInventoryList();
    } catch (error) {
        console.error('添加库存失败:', error);
        UI.showMessage(error.message || '添加库存失败', 'danger');
    }
}

/**
 * 显示更新库存模态框
 */
function showUpdateInventoryModal(inventoryId, vaccineName, currentQuantity) {
    document.getElementById('updateInventoryModal').classList.add('show');
    document.getElementById('updateInventoryId').value = inventoryId;
    document.getElementById('updateVaccineName').value = vaccineName;
    document.getElementById('updateCurrentQuantity').value = currentQuantity || 0;
    document.getElementById('updateQuantity').value = currentQuantity || 0;
}

/**
 * 关闭更新库存模态框
 */
function closeUpdateInventoryModal() {
    document.getElementById('updateInventoryModal').classList.remove('show');
}

/**
 * 处理更新库存
 */
async function handleUpdateInventory() {
    const inventoryId = document.getElementById('updateInventoryId').value;
    const currentQuantity = parseInt(document.getElementById('updateCurrentQuantity').value || '0', 10);
    const targetQuantity = parseInt(document.getElementById('updateQuantity').value || '0', 10);

    // 表单验证
    if (isNaN(targetQuantity) || targetQuantity < 0) {
        UI.showMessage('请输入有效的库存数量', 'warning');
        return;
    }

    const changeCount = targetQuantity - currentQuantity;
    if (changeCount === 0) {
        UI.showMessage('库存数量未发生变化', 'info');
        return;
    }

    try {
        const data = {
            changeCount
        };

        await HttpClient.put(`/admin/inventory/${inventoryId}`, data);

        UI.showMessage('更新库存成功', 'success');
        closeUpdateInventoryModal();

        // 重新加载库存列表
        if (currentMode === 'all') {
            await loadInventoryList();
        } else {
            await loadLowStockAlerts();
        }
    } catch (error) {
        console.error('更新库存失败:', error);
        UI.showMessage(error.message || '更新库存失败', 'danger');
    }
}

/**
 * 处理删除库存
 */
async function handleDeleteInventory(inventoryId, vaccineName) {
    const message = `确定要删除库存记录吗？\n疫苗：${vaccineName || '未关联疫苗'}`;
    
    UI.confirm(message, async () => {
        try {
            UI.showLoading();
            await HttpClient.delete(`/admin/inventory/${inventoryId}`);
            UI.showMessage('删除成功', 'success');
            
            // 重新加载列表
            if (currentMode === 'low-stock') {
                await loadLowStockAlerts();
            } else {
                await loadInventoryList();
            }
            
            UI.hideLoading();
        } catch (error) {
            console.error('删除库存失败:', error);
            UI.hideLoading();
            UI.showMessage('删除失败: ' + (error.message || '未知错误'), 'danger');
        }
    });
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

